package com.wss.lsl.mongo.demo;

import java.net.UnknownHostException;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.wss.lsl.mongo.demo.config.SpringMongoConfig2;
import com.wss.lsl.mongo.demo.model.User;

/**
 * Hello world!
 * 
 */
public class App3 {
	
	public static void main(String[] args) throws UnknownHostException {
		
		ApplicationContext context = new AnnotationConfigApplicationContext(SpringMongoConfig2.class);
		MongoOperations operations = context.getBean("mongoTemplate", MongoOperations.class);
			
		User user = new User("wss", "123456");
		
		// save 
		operations.save(user);
		System.out.println("1. user: "+user);
		
		// query
		Query searchUserQuery = new Query(Criteria.where("username").is("wss"));
		User savedUser = operations.findOne(searchUserQuery, User.class);
		System.out.println("2. saved user: "+savedUser);
		
		// update
		operations.updateFirst(searchUserQuery, Update.update("password", "654321"), User.class);
		User updatedUser = operations.findOne(searchUserQuery, User.class);
		System.out.println("3. updated user: "+updatedUser);
		
		// delete
		operations.remove(searchUserQuery, User.class);
		
		// List, it should be empty now.
		List<User> users = operations.findAll(User.class);
		System.out.println("4. number of user = "+users.size());
		System.out.println();
		
		// drop collection
		operations.dropCollection(User.class);
		
	}
}
